package com.ruoyi.web.controller.BT;

import com.ruoyi.web.Server.sys.UserService;
import com.ruoyi.web.controller.common.Constants;
import com.ruoyi.web.controller.common.base.Result;
import com.ruoyi.web.dao.BT.TagDao;
import com.ruoyi.web.domain.BT.TagCatEntity;
import com.ruoyi.web.domain.BT.TagEntity;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@Tag(name = "种子标签相关", description = Constants.FinishStatus.UNFINISHED)
@RequiredArgsConstructor
@RequestMapping("/tag")
@Validated
public class TagController {

    private final TagDao tagDao;
    private final UserService userService;


    @Operation(summary = "所有标签", description = "返回所有标签，自打上的标签")
    @GetMapping("/all_tag")
    public Result allTag() {
        List<TagEntity> tags = tagDao.all_tag();
        return Result.ok(tags);
    }

    @Operation(summary = "删除标签", description = "根据ID删除标签")
    @DeleteMapping("/delete/{id}")
    public Result deleteTag(@PathVariable Long id) {
        // 检查标签是否存在
        TagEntity tag = tagDao.findById(id);
        if (tag == null) {
            return Result.error("标签不存在");
        }

        int rows = tagDao.deleteById(id);
        if (rows > 0) {
            return Result.ok();
        } else {
            return Result.error("删除标签失败");
        }
    }

    @Operation(summary = "更新标签", description = "根据ID更新标签信息")
    @PutMapping("/update")
    public Result updateTag(@RequestBody TagEntity tag) {
        // 检查标签是否存在
        TagEntity oldTag = tagDao.findById((long)tag.getId());
        if (oldTag == null) {
            return Result.error("标签不存在");
        }

        // 检查新标签名是否已存在(排除自身)
        boolean exists = tagDao.existsByNameAndNotId(tag.getName(), (long)tag.getId());
        if (exists) {
            return Result.error("标签名已被其他标签使用");
        }

        int rows = tagDao.update(tag);
        if (rows > 0) {
            return Result.ok();
        } else {
            return Result.error("更新标签失败");
        }
    }

    @Operation(summary = "获取单个标签", description = "根据ID获取标签信息")
    @GetMapping("/{id}")
    public Result getTag(@PathVariable Long id) {
        TagEntity tag = tagDao.findById(id);
        if (tag != null) {
            return Result.ok(tag);
        } else {
            return Result.error("标签不存在");
        }
    }

    @Operation(summary = "所有分类", description = "返回所有分类,电影之类的")
    @GetMapping("/all_cat")
    public Result allCat() {
        List<TagCatEntity> tags = tagDao.all_cat();
        return Result.ok(tags);
    }
}
